package com.gitee.huanminabc.shiro.realm;

import com.gitee.huanminabc.shiro.entity.UserEntity;
import com.gitee.huanminabc.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义Realm
 */

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权, 之后就可以在接口上使用@RequiresRoles("admin")注解或者@RequiresPermissions("user:perm")注解
    //RequiresGuest  表示当前Subject是一个“guest” 非认证（非授权）的可以访问
    // 还可以通过代码SecurityUtils.getSubject()进行授权校验 subject.checkRole("admin");  subject.checkPermission("user:perm");
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 -》 授权 doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        UserEntity currentUser = (UserEntity) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission("user:perm");
        //设置当前用户的角色
        Set<String> roles = new HashSet<>();
        roles.add("test");
        info.setRoles(roles);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了 -》 认证 doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        System.out.println("userToken -> username" + userToken.getUsername());
        System.out.println("userToken -> password" + userToken.getPassword());
        //获取数据库中真实用户
        UserEntity user = userService.getUser(userToken.getUsername());
        if(user == null){ //没有这个用户,抛出异常 ,这里返回null就会抛出UnknownAccountException
            return null;
        }
        //把用户存入session
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute("user",user);
        //密码认证，shiro来做 不让你来做
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }



}

